<script setup lang="ts">
import { getPexelsList } from '@/api';
import { computed, ref, watch } from 'vue';
import Item from './Item';
import { isMobileTerminal } from '@/utils';
import { useAppStore } from '@/store';
import Pins from '@/views/pins/components/Pins';
import { usePins } from './composables';

const appStore = useAppStore();

const currentCategory = computed(() => appStore.currentCategoryGetter);
watch(currentCategory, newCategory => {
  reGetPexels({
    page: 1,
    categoryId: newCategory.id,
    searchText: searchText.value
  });
});

const searchText = computed(() => appStore.searchTextGetter);
watch(searchText, newSearchText => {
  reGetPexels({
    page: 1,
    categoryId: currentCategory.value.id,
    searchText: newSearchText
  });
});

const pexelsList = ref<any[]>([]);
let query = { page: 1, size: 20 };
const getPexels = async () => {
  if (isFinished.value) return;

  const res = await getPexelsList<{
    list: any[];
    total: number;
  }>(query);
  pexelsList.value.push(...res.list);
  query.page++;

  if (pexelsList.value.length === res.total) {
    isFinished.value = true;
  }

  isLoading.value = false;
};
const reGetPexels = (newQuery: {
  page: number;
  categoryId: string;
  searchText: string;
}) => {
  query = { ...query, ...newQuery };
  isFinished.value = false;
  pexelsList.value = [];

  getPexels();
};

const isLoading = ref<boolean>(false);
const isFinished = ref<boolean>(false);

const { onToPinsClick, isPinsVisible, currentPins, pinsTransitionEvents } =
  usePins();
</script>

<template>
  <div>
    <MInfinite
      v-model="isLoading"
      :isFinished="isFinished"
      @loadMore="getPexels"
    >
      <MWaterfall
        class="w-full px-1"
        v-bind="{
          data: pexelsList,
          nodeKey: 'id',
          columns: isMobileTerminal ? 2 : 5,
          columnGap: 10,
          rowGap: 20,
          picturePreReading: true
        }"
      >
        <template #default="{ item, width }">
          <Item :item="item" :width="width" @onToPinsClick="onToPinsClick" />
        </template>
      </MWaterfall>
    </MInfinite>

    <Transition :css="false" v-on="pinsTransitionEvents">
      <Pins v-if="isPinsVisible" :id="currentPins.id!" />
    </Transition>
  </div>
</template>
